package com.dianxun.exam.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dianxun.exam.MainApplication;
import com.dianxun.exam.R;
import com.dianxun.exam.common.AppConfig;
import com.dianxun.exam.common.AppKeyManager;
import com.dianxun.exam.common.base.BaseActivity;
import com.dianxun.exam.entity.AnswerBean;
import com.dianxun.exam.entity.AnswerBeanDao;
import com.dianxun.exam.entity.ChoiceListBean;
import com.dianxun.exam.entity.DaoSession;
import com.dianxun.exam.entity.ItemListBean;
import com.dianxun.exam.entity.JudgmentListBean;
import com.dianxun.exam.entity.TikuSubjectChoiceItemListBean;
import com.dianxun.exam.entity.TikuSubjectChoiceItemListBeanDao;
import com.dianxun.exam.entity.TikuSubjectChoiceListBean;
import com.dianxun.exam.entity.TikuSubjectChoiceListBeanDao;
import com.dianxun.exam.entity.TikuSubjectJudgmentListBean;
import com.dianxun.exam.entity.TempSaveBean;
import com.dianxun.exam.entity.TempSaveBeanDao;
import com.dianxun.exam.entity.TikuBean;
import com.dianxun.exam.entity.TikuBeanDao;
import com.dianxun.exam.entity.TikuSubjectJudgmentListBeanDao;
import com.dianxun.exam.ui.widget.WaitDialog;
import com.dianxun.exam.utils.RxTimeTool;
import com.dianxun.exam.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 准备考试
 */
public class ExamReadyActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.tv_back)
    TextView tv_back;
    @BindView(R.id.list_paper)
    RecyclerView list_paper;
    private DaoSession daoSession;
    private TikuBeanDao tikuBeanDao;
    private TikuSubjectJudgmentListBeanDao tikuSubjectJudgmentListBeanDao;
    private TikuSubjectChoiceListBeanDao tikuSubjectChoiceListBeanDao;
    private TikuSubjectChoiceItemListBeanDao tikuSubjectChoiceItemListBeanDao;
    private AnswerBeanDao answerBeanDao;
    private TempSaveBeanDao tempSaveBeanDao;
    private PaperAdapter paperAdapter;
    private WaitDialog mWaitDialog;
    private TikuBean tikuBean;
    private String mockTikuId;
    private boolean isOfficial;

    @Override
    protected int getContentView() {
        return R.layout.activity_exam_ready;
    }

    @Override
    protected void initView() {
        mWaitDialog = new WaitDialog(self);
        mWaitDialog.setMessage("试卷生成中，请稍等。。。");
        mWaitDialog.setCancelable(false);

        list_paper.setLayoutManager(new LinearLayoutManager(self));
        paperAdapter = new PaperAdapter();
        paperAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                tikuBean = (TikuBean) adapter.getData().get(position);

                // 随机考试
                if (tikuBean.getCategory().equals("1")) {
                    List<AnswerBean> answerBeans = answerBeanDao.queryBuilder().where(AnswerBeanDao.Properties.UserId.eq(AppConfig.getInstance().getUserId()),
                            AnswerBeanDao.Properties.TikuId.eq(tikuBean.getTikuId())).list();
                    if (answerBeans != null && answerBeans.size() > 0) {
                        Bundle b = new Bundle();
                        b.putString(ExamActivity.EXTRA_TIKUID, tikuBean.getTikuId());
                        jumpActivity(ExamFinishActivity.class, b);
                    } else {
                        long startTimeMills = RxTimeTool.string2Milliseconds(tikuBean.getStartDate(), new SimpleDateFormat(RxTimeTool.DATE_FORMAT));
//                      long endTimeMills = RxTimeTool.string2Milliseconds(tikuBean.getEndDate(), new SimpleDateFormat(RxTimeTool.DATE_FORMAT));
                        long curTimeMills = RxTimeTool.getCurTimeMills();
                        if (curTimeMills < startTimeMills) {
                            toast("还未到考试时间，无法考试");
                            return;
                        }
//                      if (curTimeMills > endTimeMills) {
//                          toast("考试时间已过，无法考试");
//                          return;
//                      }
                        final String[] items = {"正式考试", "模拟考试"};
                        AlertDialog.Builder listDialog =
                                new AlertDialog.Builder(self);
                        listDialog.setTitle("请选择");
                        listDialog.setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        isOfficial = true;
                                        startExam();
                                        break;
                                    case 1:
                                        isOfficial = false;
                                        startExam();
                                        break;
                                }
                            }
                        });
                        listDialog.show();
                    }
                } else {
                    final String[] items = {"正式考试"};
                    AlertDialog.Builder listDialog =
                            new AlertDialog.Builder(self);
                    listDialog.setTitle("请选择");
                    listDialog.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case 0:
                                    isOfficial = true;
                                    startExam();
                                    break;
                            }
                        }
                    });
                    listDialog.show();

                }
            }
        });
        list_paper.setAdapter(paperAdapter);

        daoSession = ((MainApplication) getApplication()).getDaoSession();
        answerBeanDao = daoSession.getAnswerBeanDao();
        tempSaveBeanDao = daoSession.getTempSaveBeanDao();
        tikuBeanDao = daoSession.getTikuBeanDao();
        tikuSubjectJudgmentListBeanDao = daoSession.getTikuSubjectJudgmentListBeanDao();
        tikuSubjectChoiceListBeanDao = daoSession.getTikuSubjectChoiceListBeanDao();
        tikuSubjectChoiceItemListBeanDao = daoSession.getTikuSubjectChoiceItemListBeanDao();
    }

    Observer<Object> observer = new Observer<Object>() {

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(Object value) {

        }

        @Override
        public void onError(Throwable e) {
            if (isFinishing()) {
                return;
            }
            if (mWaitDialog.isShowing()) {
                mWaitDialog.dismiss();
            }
            toast(e.getMessage());
        }

        @Override
        public void onComplete() {
            if (isFinishing()) {
                return;
            }
            if (mWaitDialog.isShowing()) {
                mWaitDialog.dismiss();
            }
            Bundle b = new Bundle();
            if (isOfficial) {
                b.putString(ExamActivity.EXTRA_TIKUID, tikuBean.getTikuId());
                jumpActivity(ExamActivity.class, b);
            } else {
                b.putSerializable(ExamActivity.EXTRA_TIKUID, mockTikuId);
                jumpActivity(ExamMockActivity.class, b);
            }
        }
    };

    private void startExam() {
        if (!mWaitDialog.isShowing()) {
            mWaitDialog.show();
        }
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) {
                try {
                    List<TempSaveBean> tempSaveBeanList = tempSaveBeanDao.queryBuilder()
                            .where(TempSaveBeanDao.Properties.TikuId.eq(tikuBean.getTikuId()),
                                    TempSaveBeanDao.Properties.UserId.eq(AppConfig.getInstance().getUserId()))
                            .list();
                    // 考试开始了或者模拟考试，生成题目
                    if (tempSaveBeanList.size() == 0 || !isOfficial) {
                        // 随机考试
                        if (tikuBean.getCategory().equals("1")) {
                            List<TikuSubjectJudgmentListBean> tikuSubjectJudgmentListBeans = tikuSubjectJudgmentListBeanDao.queryBuilder()
                                    .where(TikuSubjectJudgmentListBeanDao.Properties.ExamType.in(tikuBean.getExamType().split(","))).list();
                            List<TikuSubjectChoiceListBean> tikuSubjectChoice0ListBeans = tikuSubjectChoiceListBeanDao.queryBuilder()
                                    .where(TikuSubjectChoiceListBeanDao.Properties.ExamType.in(tikuBean.getExamType().split(","))).where(TikuSubjectChoiceListBeanDao.Properties.Type.eq(0)).list();
                            List<TikuSubjectChoiceListBean> tikuSubjectChoice1ListBeans = tikuSubjectChoiceListBeanDao.queryBuilder()
                                    .where(TikuSubjectChoiceListBeanDao.Properties.ExamType.in(tikuBean.getExamType().split(","))).where(TikuSubjectChoiceListBeanDao.Properties.Type.eq(1)).list();
                            List<TikuSubjectChoiceItemListBean> tikuSubjectChoiceItemListBeans = tikuSubjectChoiceItemListBeanDao.queryBuilder().list();

                            if (tikuBean.getJudgmentNum() > 0) {
                                int size = tikuSubjectJudgmentListBeans.size() / tikuBean.getJudgmentNum();
                                List<TikuSubjectJudgmentListBean> selecttempList = new ArrayList<>();
                                for (int i = 0; i < tikuBean.getJudgmentNum(); i++) {
                                    List<TikuSubjectJudgmentListBean> tempList = tikuSubjectJudgmentListBeans.subList(i * size, (i + 1) * size);
                                    selecttempList.add(tempList.get((int) (Math.random() * (tempList.size()))));
                                }
                                tikuSubjectJudgmentListBeans = selecttempList;
                            }

                            if (tikuBean.getChoice0Num() > 0) {
                                int size = tikuSubjectChoice0ListBeans.size() / tikuBean.getChoice0Num();
                                List<TikuSubjectChoiceListBean> selecttempList = new ArrayList<>();
                                for (int i = 0; i < tikuBean.getChoice0Num(); i++) {
                                    List<TikuSubjectChoiceListBean> tempList = tikuSubjectChoice0ListBeans.subList(i * size, (i + 1) * size);
                                    selecttempList.add(tempList.get((int) (Math.random() * (tempList.size()))));
                                }
                                tikuSubjectChoice0ListBeans = selecttempList;
                            }

                            if (tikuBean.getChoice1Num() > 0) {
                                int size = tikuSubjectChoice1ListBeans.size() / tikuBean.getChoice1Num();
                                List<TikuSubjectChoiceListBean> selecttempList = new ArrayList<>();
                                for (int i = 0; i < tikuBean.getChoice1Num(); i++) {
                                    List<TikuSubjectChoiceListBean> tempList = tikuSubjectChoice1ListBeans.subList(i * size, (i + 1) * size);
                                    selecttempList.add(tempList.get((int) (Math.random() * (tempList.size()))));
                                }
                                tikuSubjectChoice1ListBeans = selecttempList;
                            }

                            //                        Collections.shuffle(tikuSubjectJudgmentListBeans);
                            //                        Collections.shuffle(tikuSubjectChoice0ListBeans);
                            //                        Collections.shuffle(tikuSubjectChoice1ListBeans);
                            //                        tikuSubjectJudgmentListBeans = tikuSubjectJudgmentListBeans.subList(0, tikuBean.getJudgmentNum());
                            //                        tikuSubjectChoice0ListBeans = tikuSubjectChoice0ListBeans.subList(0, tikuBean.getChoice0Num());
                            //                        tikuSubjectChoice1ListBeans = tikuSubjectChoice1ListBeans.subList(0, tikuBean.getChoice1Num());

                            // 判断题生成
                            List<JudgmentListBean> judgmentListBeans = new ArrayList<>();
                            int sequ = 1;
                            for (TikuSubjectJudgmentListBean bean : tikuSubjectJudgmentListBeans) {
                                JudgmentListBean entity = new JudgmentListBean();
                                entity.setItemId(Utils.getUUID());
                                entity.setMasterId(tikuBean.getTikuId());
                                entity.setJudgmentId(bean.getJudgmentId());
                                entity.setSequ(sequ);
                                sequ++;
                                entity.setScore(tikuBean.getJudgmentScoreAvg());
                                entity.setItemName(bean.getName());
                                entity.setItemAnswer(bean.getAnswer());

                                // 自动填答案
                                //                          entity.setAnswer(Integer.parseInt(bean.getAnswer()));

                                judgmentListBeans.add(entity);
                            }
                            tikuBean.setJudgmentList(judgmentListBeans);
                            // 单选题生成
                            List<ChoiceListBean> choice0List = new ArrayList<>();
                            for (TikuSubjectChoiceListBean bean : tikuSubjectChoice0ListBeans) {
                                ChoiceListBean entity = new ChoiceListBean();
                                entity.setItemId(Utils.getUUID());
                                entity.setMasterId(tikuBean.getTikuId());
                                entity.setChoiceId(bean.getChoiceId());
                                entity.setSequ(sequ);
                                sequ++;
                                entity.setScore(tikuBean.getChoice0ScoreAvg());
                                entity.setItemName(bean.getName());

                                List<ItemListBean> itemEntities = new ArrayList<>();
                                for (TikuSubjectChoiceItemListBean itemBean : tikuSubjectChoiceItemListBeans) {
                                    if (itemBean.getMasterId().equals(bean.getChoiceId())) {
                                        ItemListBean itemEntity = new ItemListBean();
                                        itemEntity.setItemId(Utils.getUUID());
                                        itemEntity.setMasterId(entity.getItemId());
                                        itemEntity.setChoiceItemId(itemBean.getItemId());
                                        itemEntity.setItemName(itemBean.getAnswer());
                                        itemEntity.setItemAnswer(itemBean.getFlag());

                                        // 自动填答案
                                        //                                  itemEntity.setAnswer(Integer.parseInt(itemBean.getFlag()));

                                        itemEntity.setSequ(sequ);
                                        sequ++;
                                        itemEntities.add(itemEntity);
                                    }
                                }
                                entity.setItemList(itemEntities);
                                choice0List.add(entity);
                            }
                            tikuBean.setChoice0List(choice0List);
                            // 多选题生成
                            List<ChoiceListBean> choice1List = new ArrayList<>();
                            for (TikuSubjectChoiceListBean bean : tikuSubjectChoice1ListBeans) {
                                ChoiceListBean entity = new ChoiceListBean();
                                entity.setItemId(Utils.getUUID());
                                entity.setMasterId(tikuBean.getTikuId());
                                entity.setChoiceId(bean.getChoiceId());
                                entity.setSequ(sequ);
                                sequ++;
                                entity.setScore(tikuBean.getChoice1ScoreAvg());
                                entity.setItemName(bean.getName());

                                List<ItemListBean> itemEntities = new ArrayList<>();
                                for (TikuSubjectChoiceItemListBean itemBean : tikuSubjectChoiceItemListBeans) {
                                    if (itemBean.getMasterId().equals(bean.getChoiceId())) {
                                        ItemListBean itemEntity = new ItemListBean();
                                        itemEntity.setItemId(Utils.getUUID());
                                        itemEntity.setMasterId(entity.getItemId());
                                        itemEntity.setChoiceItemId(itemBean.getItemId());
                                        itemEntity.setSequ(sequ);
                                        sequ++;
                                        itemEntity.setItemName(itemBean.getAnswer());
                                        itemEntity.setItemAnswer(itemBean.getFlag());

                                        // 自动填答案
                                        //                                  itemEntity.setAnswer(Integer.parseInt(itemBean.getFlag()));

                                        itemEntities.add(itemEntity);
                                    }
                                }
                                entity.setItemList(itemEntities);
                                choice1List.add(entity);
                            }
                            tikuBean.setChoice1List(choice1List);
                            if (isOfficial) {
                                tikuBeanDao.update(tikuBean);
                            } else {
                                TikuBean tikuBeanMock = null;
                                try {
                                    tikuBeanMock = (TikuBean) tikuBean.clone();
                                    // 重新生成id，清除用户
                                    Long l = null;
                                    tikuBeanMock.setId(l);
                                    mockTikuId = UUID.randomUUID().toString();
                                    tikuBeanMock.setTikuId(mockTikuId);
                                    tikuBeanMock.setShareUserIdList(new ArrayList<String>());
                                    tikuBeanDao.insert(tikuBeanMock);
                                } catch (CloneNotSupportedException e) {

                                }
                            }
                        }
                    }
                    emitter.onComplete();
                } catch (Exception e) {
                    emitter.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    @Override
    protected void onResume() {
        super.onResume();
        List<TikuBean> tikuBeans = tikuBeanDao.queryBuilder().list();
        List<TikuBean> myTikuBeans = new ArrayList<>();
        for (TikuBean bean : tikuBeans) {
            if (bean.getShareUserIdList().contains(AppConfig.getInstance().getUserId())) {
                myTikuBeans.add(bean);
            }
        }
        if (myTikuBeans.size() == 0) {
            toast("当前用户没有考试！");
            finish();
        } else {
            paperAdapter.setNewData(myTikuBeans);
        }
    }

    @Override
    protected void initListeners() {
        tv_back.setOnClickListener(this);
    }

    public class PaperAdapter extends BaseQuickAdapter<TikuBean, BaseViewHolder> {

        public PaperAdapter() {
            super(R.layout.item_exam_ready_layout, null);
        }

        @Override
        protected void convert(BaseViewHolder helper, TikuBean tikuBean) {
            helper.setText(R.id.tv_batch, tikuBean.getBatchNo() + "/" + tikuBean.getBatchName());
            helper.setText(R.id.tv_paper_no, tikuBean.getLotNo());
            List<TempSaveBean> tempSaveBeanList = tempSaveBeanDao.queryBuilder()
                    .where(TempSaveBeanDao.Properties.TikuId.eq(tikuBean.getTikuId()),
                            TempSaveBeanDao.Properties.UserId.eq(AppConfig.getInstance().getUserId()))
                    .orderAsc(TempSaveBeanDao.Properties.LeftTime)
                    .list();
            if (tempSaveBeanList.size() > 0) {
                TempSaveBean tempSaveBean = tempSaveBeanList.get(0);
                helper.setText(R.id.tv_total_time_title, "剩余时间");
                helper.setText(R.id.tv_time, (tempSaveBean.getLeftTime() / 60) + "分钟");
                helper.setText(R.id.tv_paper_status, "未完成");
            } else {
                helper.setText(R.id.tv_total_time_title, "考试时长");
                helper.setText(R.id.tv_time, tikuBean.getTotalTime() + "分钟");
                helper.setText(R.id.tv_paper_status, "未开始");
            }
            List<AnswerBean> answerBeans = answerBeanDao.queryBuilder().where(AnswerBeanDao.Properties.UserId.eq(AppConfig.getInstance().getUserId()),
                    AnswerBeanDao.Properties.TikuId.eq(tikuBean.getTikuId())).list();
            if (answerBeans != null && answerBeans.size() > 0) {
                helper.setText(R.id.tv_total_time_title, "考试时长");
                helper.setText(R.id.tv_time, tikuBean.getTotalTime() + "分钟");
                helper.setText(R.id.tv_paper_status, "已交卷");
            }
            helper.setText(R.id.tv_startDate, tikuBean.getStartDate());
            helper.setText(R.id.tv_endDate, tikuBean.getEndDate());
            helper.setText(R.id.tv_score, tikuBean.getTotalScore() + "分");
            String displayName = getIntent().getExtras().getString(AppKeyManager.SP_DISPLAYNAME);
            helper.setText(R.id.tv_persion_name, displayName);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
        }
    }
}
